import { defineComponent, ref, watch } from "vue";
import util from "@/libs/util";
import columns from "./columns";
import { Modal } from "view-ui-plus";
import { useTableList, useRowSelect } from "@/hooks";
import { getPage } from "@/api/baseData/testStandard";
import { onSave } from "@/api/baseData/testProject";
import { getDictionary } from "@/api/common";

export default defineComponent({
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    projectNameCode: {
      type: String,
      default: "",
    },
  },
  emits: ["update:modelValue", "change"],
  setup(props, { emit }) {
    // ref
    const standardIcrud = ref<HTMLElement>();
    // option配置
    const iCrudOptions = util.env.iCrudOptions;
    // 列表数据
    const list = ref<any>([]);
    // 列表配置
    const columnsTable = columns;
    // 跨页多选
    const selectionRowOptions = {
      selectKey: "id",
      batchRemove: { show: false },
    };

    const standardType = ref([]);

    const loading = ref(false);

    getDictionary({ dictType: "standard_type" }).then((res: any) => {
      standardType.value = res;
    });

    const { selectItems, setCheckedItem } = useRowSelect();

    let { getApiTableList, total } = useTableList(getPage, list);

    const handleSubmit = () => {
      const ids = selectItems.value.map((item) => item.id).join(",");
      onSave({ standardIds: ids, projectNameCode: props.projectNameCode }).then(
        (res) => {
          emit("change");
          emit("update:modelValue", false);
        }
      );
    };

    const onCancel = () => {
      emit("update:modelValue", false);
    };

    const setStandardType = ({ row }) => {
      const obj = standardType.value.find(
        (item) => item.dictValue == row.standardType
      );

      return obj && obj.dictLabel;
    };

    //刷新数据
    return () => {
      const searchoptions = { labelWidth: 150 };
      return (
        <Modal
          model-value={props.modelValue}
          width={1200}
          title="添加"
          onOnOk={handleSubmit}
          onOnCancel={onCancel}
          loading={loading.value}
        >
          <i-crud
            title="检测标准"
            ref={standardIcrud}
            form-options={iCrudOptions.formOptions}
            page-options={{ ...iCrudOptions.pageOptions, total: total.value }}
            search-options={searchoptions}
            selection-row={selectionRowOptions}
            border={true}
            data={list.value}
            columns={columnsTable}
            fetch-data={getApiTableList}
            onOnSelectionChange={setCheckedItem}
            toolbarOptions={{ show: false, items: ["refresh"] }}
            addFormOptions={{
              show: false,
            }}
            v-slots={{ standardType: setStandardType }}
          ></i-crud>
        </Modal>
      );
    };
  },
});
